import React, { Component } from 'react'
import { Button, Col, Icon, Input, message, Row, Tag } from 'antd'
import * as homework from '../../constant/homework-request-status'
import '../../less/index.less'
import { TwsReactMarkdownPreview } from 'tws-antd'
import { STUDENT_MODIFY_ASSIGNMENT_STATUS } from '../../constant/notification-status'
import { FormattedMessage } from 'react-intl'
import { convertContent, getLangFromLocalStorage } from '../../constant/lang-util'
import QuizSuggestionBox from '../common/quiz-suggestion-box'
import QuizNoteModal from "./quiz-note-modal";

const TIMEOUT = 3000

export default class HomeworkQuiz extends Component {
  constructor (props) {
    super(props)
    this.state = {
      userAnswerRepo: props.quiz.userAnswer,
      branch: props.quiz.answerBranch,
      loading: false,
      runningResult: props.runningLogs.result,
      status: props.runningLogs.status,
      submissionId: 0,
      isQuizNoteModalVisible: false,
      noteContent: ''
    }
  }
  componentWillReceiveProps (props) {
    const { userAnswer, answerBranch } = props.quiz
    const { result, status } = props.runningLogs
    this.setState({ userAnswerRepo: userAnswer, branch: answerBranch, runningResult: result, status: status })
  }

  buildSubmitData (userAnswerRepo, branch) {
    const {assignmentId, quiz} = this.props
    return {
      assignmentId,
      quizId: quiz.id,
      userAnswerRepo,
      branch
    }
  }
  buildNotification () {
    const {quiz, assignmentId, programId, taskId} = this.props
    return {
      programId,
      taskId,
      assignmentId,
      quizId: quiz.id,
      type: STUDENT_MODIFY_ASSIGNMENT_STATUS,
      appType: 'homeworkQuiz'
    }
  }

  submit () {
    const {userAnswerRepo, branch} = this.state
    const reg = new RegExp('^((http|https)://)*?(www.)*?(git).*?$')
    const url = userAnswerRepo || ''
    const defaultBranch = branch || 'master'
    const notification = this.buildNotification()
    if (!reg.test(url)) {
      message.info(convertContent('请输入正确的git仓库地址'))
    } else {
      const data = this.buildSubmitData(userAnswerRepo, defaultBranch)
      this.props.submitAnswer(data, (submissionId) => {
        this.loadLogs(submissionId)
        this.props.addNotification(notification)
      })
    }
  }

  getResult (status) {
    return status === homework.status.SUCCESS ? message.success(convertContent('编译通过'))
      : message.error(convertContent('编译不通过'))
  }

  loadLogs (submissionId) {
    const {assignmentId, quiz, taskId} = this.props
    this.props.getRunningLogs(taskId, assignmentId, quiz.id, submissionId, (result) => {
      const status = result.status
      const logs = result.result
      this.setState({runningResult: logs, status: status, loading: true})

      if (status !== homework.status.SUCCESS && status !== homework.status.ERROR) {
        setTimeout(() => {
          this.loadLogs(submissionId)
        }, TIMEOUT)
      } else {
        this.getResult(status)
        this.setState({loading: false})
      }
    })
  }

  getRunningResult () {
    const status = this.state.status
    const textResult = homework.result[status] || {}
    const submission = this.props.runningLogs
    return (<div className={submission.id ? '' : 'hidden'}>
      <label>
        <Tag color={textResult.color}>
          {(status === 3 || status === 6) ? <Icon type='sync' spin /> : ''}
          {convertContent(textResult.content)}
        </Tag>
      </label>
      <div className='result-content'>
        {convertContent(this.state.runningResult)}
      </div>
    </div>)
  }

  getStudentAnswer () {
    const status = this.state.status
    return status === 2
        ? <Tag color='#87d068'>{convertContent('编译通过')}</Tag>
        : <Tag color='red'>{convertContent('编译不通过')}</Tag>
  }

  showModal = () => {
    this.setState({
      isQuizNoteModalVisible: true,
    });
  };

  handleOk = () => {
    this.setState({
      isQuizNoteModalVisible: false,
      noteContent: ''
    });
    this.handleSubmit()
  };

  handleCancel = () => {
    this.setState({
      isQuizNoteModalVisible: false,
    });
  };

  handleSubmit = () => {
    const {noteContent} = this.state
    const {programId, assignmentId, taskId, user, reviewQuiz} = this.props
    const {studentId, quizId} = reviewQuiz
    const tutorId = user.id
    const quizType = 'HOMEWORK_QUIZ'
    const values = {programId, taskId, assignmentId, quizId, studentId, tutorId, quizType, noteContent}
    this.props.submitNote(values)
  };

  handelChangeNote(value) {
    this.setState({
      noteContent: value
    })
  }

  render () {
    const {loading, userAnswerRepo, branch, isQuizNoteModalVisible} = this.state
    const {quiz = {}, reviewQuiz,settings} = this.props
    const {templateRepository, userAnswer} = quiz
    const isFinished = userAnswer !== ''
    const disable = this.props.isInstructor ? true : ''
    const lang = getLangFromLocalStorage()
    const description = quiz[`description_${lang}`] || quiz.description

    const unSubmitted = <div><h3><FormattedMessage id='提交作业' /></h3>
      <div className='margin-t-2 mark-down-wrap'>
        <TwsReactMarkdownPreview source={convertContent('编程题模板库地址') + '：' + templateRepository} />
        <div style={{background: 'white', margin: '-7px 0px 0px 0px'}}>
          <Row>
            <Col span={10} className='margin-l-2'>
              <Input
                addonBefore={<FormattedMessage id='git仓库地址' />}
                value={userAnswerRepo}
                onChange={e => this.setState({userAnswerRepo: e.target.value})}
              />
            </Col>
          </Row>
          <Row>
            <Col span={10} className='margin-t-2 margin-l-2'>
              <Input
                addonBefore={<FormattedMessage id='git仓库分支' />}
                value={branch}
                placeholder={convertContent('默认master')}
                onChange={e => this.setState({branch: e.target.value})}
              />
            </Col>
          </Row>
          <Row>
            <Col className='margin-t-2 margin-l-2 margin-b-1'>
              <Button style={{width: 250}} disabled={disable} loading={loading}
                onClick={this.submit.bind(this)}><FormattedMessage id='提交代码地址' /></Button>
              <p><FormattedMessage id='编程题正在运行时请勿刷新该页面' /></p>
            </Col>
          </Row>
        </div>
        {this.getRunningResult()}
      </div>
    </div>
    const submitted = <div><h3><FormattedMessage id='我的答案' /></h3>
      {
        reviewQuiz.id
          ? <span className='submit-time-box'>
            <Icon type='clock-circle' />
            {reviewQuiz.createTime}
          </span>
          : ''
      }
      {this.props.preview
        ? <a href={userAnswerRepo} target='_blank'>{userAnswerRepo}</a>
        : <div className='margin-t-2 mark-down-wrap'>
          <TwsReactMarkdownPreview source={convertContent('编程题模板库地址') + '：' + templateRepository} />
          <div style={{background: 'white', margin: '-7px 0px 0px 0px'}}>
            <Row>
              <Col span={10} className='margin-l-2'>
                <Input addonBefore={<FormattedMessage id='git仓库地址' />} value={userAnswerRepo}
                  onChange={e => this.setState({userAnswerRepo: e.target.value})} />
              </Col>
            </Row>
            <Row>
              <Col span={10} className='margin-t-2 margin-l-2'>
                <Input addonBefore={<FormattedMessage id='git仓库分支' />} value={branch}
                  onChange={e => this.setState({branch: e.target.value})} />
              </Col>
            </Row>
            <Row>
              <Col className='margin-t-2 margin-l-2 margin-b-1'>
                <Button style={{width: 250}} loading={loading} disabled={disable}
                  onClick={this.submit.bind(this)}><FormattedMessage id='再次提交代码' /></Button>
                <p><FormattedMessage id='编程题正在运行时请勿刷新该页面' /></p>
              </Col>
            </Row>
          </div>
          {this.getRunningResult()}
        </div>}
    </div>

    return <div>
      <div className='margin-t-3'>
        <h3><FormattedMessage id='作业内容' /></h3>
        <div className='margin-t-2 mark-down-wrap'>
          <TwsReactMarkdownPreview source={description} />
        </div>
      </div>
      <QuizSuggestionBox
        settings={settings}
        quiz={quiz}
        submit={this.props.submitQuizSuggestion}
      />
      <div className='margin-t-3'>
        {this.props.isInstructor ? unSubmitted
          : this.props.isExcellence ? <div>
            <h3><FormattedMessage id='优秀答案' /></h3>
            <div className='margin-t-2 mark-down-wrap'>
              <TwsReactMarkdownPreview source={quiz.userAnswer} />
            </div>
          </div>
            : this.props.isTutor ? <div>
              <Row>
                <Col span={2}>
                  <h3><FormattedMessage id='学生答案' /></h3>
                </Col>
                <Col span={3}>
                  {
                    reviewQuiz.id !== null ? <a onClick={this.showModal}><FormattedMessage id='添加备忘录' /></a> : ''
                  }
                  <QuizNoteModal
                      isQuizNoteModalVisible={isQuizNoteModalVisible}
                      handleOk={this.handleOk}
                      handleCancel={this.handleCancel}
                      handelChangeNote={this.handelChangeNote.bind(this)}
                  />
                </Col>
              </Row>
              {
                  reviewQuiz.id
                    ? <span className='submit-time-box'>

                      <Icon type='clock-circle' />
                      {reviewQuiz.createTime}
                    </span>
                    : ''
                }
              <br />
              {
                isFinished
                  ? this.getStudentAnswer()
                  : ''
              }
              <div className='margin-t-2 mark-down-wrap'>
                {isFinished ?
                  <div>
                    <h4><FormattedMessage id='答案分支' />：{quiz.answerBranch}</h4><br/>
                    <TwsReactMarkdownPreview source={quiz.userAnswer} />
                  </div>
                  : <FormattedMessage id='学生还没有提交答案' />}
              </div>
            </div>
              : isFinished ? submitted : unSubmitted
        }
      </div>
    </div>
  }
}
